<?php
namespace App\Models;

class Favorable extends BaseModel
{
    protected $table = "favorable";

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }

    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    // 获取优惠券列表
    public function favorableList($request)
    {
        $where = [];
        if ($request['type']) {
            $where['type'] = $request['type'];
        } else {
            $where['type'] = 1;
        }
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    /**
     * 获取单条优惠码
     */
    public function getFavorableCode($fav_id)
    {
        $data = $this->getOne(array('id' => $fav_id));
        $favorblecodeArr = json_decode($data['code_pool']);
        return $favorblecodeArr;
    }

    public function getFavorableInfo($request)
    {
        $where['id'] = $request['id'];
        $res = $this->getOne($where);
        if (!$res) {
            return ['state' => '0', 'msg' => '获取优惠券详情失败'];
        }
        $res = $res->toArray();
        return ['state' => '1', 'msg' => '获取优惠券详情成功', 'data' => $res];

    }

    /**
     * @param $num生成优惠码
     */
    public function createCode($num)
    {
        $rand_code = [];
        for ($i = 0; $i < $num; $i++) {
            $_tempcode = '';
            for ($j = 0; $j < 15; $j++) {
                $_tempcode .= rand(0, 9);
            }
            $rand_code[] = $_tempcode;
        }
        return $rand_code;
    }

    /**
     * 新增优惠券
     * @param $request
     * @return array
     */
    public function addFavorable($request)
    {
//         $av_object = $request['av_object'];
        $name = '折扣券';
        if ($request['type'] == 2) {
            $name = '代金券';
        }
        if ($request['type'] == 3) {
            $name = '体验券';
        }
        $title = $request['title']; // 折扣券名
        $all_num = $request['num']; // 发放数量
        $type = $request['type']; // 优惠券类别
        $group_type = $request['user_type'];
        if (!empty($group_type)) {
            $data['group_type'] = implode(',',$group_type);
        }
        if (empty($title) || empty($all_num) || empty($type) || empty($user)) {
            return $name . '信息填写不完整';
        }
        $data['title'] = $title;
        $data['id_no'] = date("Ymd") . time();
        $data['num'] = $all_num;
        $data['type'] = $type;
        $data['rest_num'] = $all_num;
        $data['recive_num'] = intval($request['recive_num']) ? intval($request['recive_num']) : 1;
        $data['consume_money'] = $request['consume_money'] ? $request['consume_money'] : 0;
        $data['discount'] = $request['discount'] ? $request['discount'] : 0;
        $data['cash'] = $request['cash'] ? $request['cash'] : 0;
        $data['code_pool'] = json_encode($this->createCode($all_num));
        $data['desc'] = $request['desc'];
        if ($request['pics']) {
            $img = upImgs($request['pics'], 'favorable');
            $data['imgs'] = $img;
        }
        $data['start_time'] = date('Y-m-d', time());
        $data['end_time'] = $request['end_time'];
        $data['created_at'] = date('Y-m-d H:i:s', time());
        if ($request['id']) {
            $where['id'] = $request['id'];
            $res = $this->up($where, $data);
            if (!$res) {
                return $name . "编辑失败";
            }
            return $name . "编辑成功";
        }
        $res = $this->add($data);
        if (!$res) {
            return $name . '新增失败';
        }
        return $name . '新增成功';
    }

    /**
     * 核销
     */
    public function writeOff($request)
    {
        $code = $request['code'];
        if ($request['fav_id']) {
            $where['id'] = $request['fav_id'];
        }
        $where['code_pool'] = array('like', '%"' . $code . '"%');
        $res = $this->getOne($where);
        if (!$res) {
            return ['state' => 0, 'msg' => '优惠券核验码错误'];
        }
        $my_favor['code_pool'] = $code;
        $myFavorable = new MyFavorable();
        $code_info = $myFavorable->getOne($my_favor);
        if ($code_info) {
            $code_info = $code_info->toArray();
        }
        $data['user_id'] = $code_info['user_id'];
        $data['favorable_id'] = $code_info['favorable_id'];
        $data['my_favorable_id'] = $code_info['favorable_id'];
        $data['code'] = $request['code'];
        $data['type'] = $res['type'];
        $data['status'] = 0;
        $data['created_at'] = date('Y-m-d', time());
        $data['updated_at'] = date('Y-m-d', time());
        $favorable_used = new FavorableUsed();
        $res = $favorable_used->add($data);
        $update['state'] = 1;
        $u_where['id'] = $code_info['id'];
        $u_res = $myFavorable->up($u_where, $update);
        if (!$res) {
            return ['state' => 0, 'msg' => '优惠券核验失败'];
        }
        return ['state' => 1, 'msg' => '优惠券核验成功'];
    }

    // 获取优惠券列表
    public function favorable($request)
    {
        $where = [];
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        $my_fav = new MyFavorable();
        // 判断该券是否已经领取
        foreach ($rows['data'] as $k => $v) {
            $has_where['user_id'] = $request['mid'];
            $has_where['favorable_id'] = $v['id'];
            $res = $my_fav->getOne($has_where);
            if ($res) {
                $rows['data'][$k]['has'] = 1;
            } else {
                $rows['data'][$k]['has'] = 0;
            }
        }
        return $rows;
    }

    public function getFavorable($request)
    {
        $fav_id = $request['f_id'];
        $code_pool = $this->getFavorableCode($fav_id);
        $favor_info = $this->getOne(array('id' => $fav_id));

        if (!$favor_info) {
            return ['state' => 0, 'msg' => "优惠券信息错误"];
        }
        // 判断优惠券是否已经领取完
        if ($favor_info['rest_num'] == 0) {
            return ['state' => 0, 'msg' => "该优惠券已经领取完了"];
        }
        $favor_info = $favor_info->toArray();
        $code_num = count($code_pool);
        $code = $code_pool[rand(0, $code_num)];
        $data['user_id'] = $request['mid'];
        $data['favorable_id'] = $favor_info['id'];
        $data['num'] = $request['num'] ? $request['num'] : 1;
        $data['code_pool'] = $code;
        $data['start_time'] = $favor_info['start_time'];
        $data['end_time'] = $favor_info['end_time'];
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $my_fav = new MyFavorable();
        // 判断是否领取该优惠券
        $my_favwhere['favorable_id'] = $favor_info['id'];
        $my_favwhere['user_id'] = $request['mid'];
        $is_has = $my_fav->getOne($my_favwhere);
        if ($is_has) {
            return ['state' => 0, 'msg' => "该优惠券已经领取过了"];
        }
        // 更新优惠券数量
        $updata['rest_num'] = intval($favor_info['rest_num']) - $data['num'];
        $where['id'] = $favor_info['id'];
        $this->up($where, $updata);
        $res = $my_fav->add($data);
        if (!$res) {
            return ['state' => 0, 'msg' => "优惠券领券失败"];
        }
        return ['state' => 1, 'msg' => "优惠券领券成功"];

    }

    /**
     * 删除折扣券
     * @param $request
     * @return array
     */
    public function delFavorable($request)
    {
        $where['id'] = $request['id'];
        $res = $this->del($where);
        $my_fav = new MyFavorable();
        $fav_used = new FavorableUsed();
        $my_fav_res = $my_fav->del(array('favorable_id' => $request['id']));
        $fav_use = $fav_used->del(array('favorable_id' => $request['id']));
        if (!$res) {
            return ['state' => 0, '优惠券删除失败'];
        }
        return ['state' => 1, '优惠券删除成功'];
    }
}